/*
 * Copyright (C) 2011 FlylinkDC++ Team http://flylinkdc.blogspot.com/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifndef _WZ_SHARE_H_
#define _WZ_SHARE_H_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "resource.h"
#include "../client/SearchManager.h"
#include "../LineDlg.h"


class WzShare : public CPropertyPageImpl<WzShare>
{
public:
    enum { IDD = IDD_WIZARD_SHARE };

    // Construction
    WzShare() : CPropertyPageImpl<WzShare>(  CTSTRING(WIZARD_TITLE) )	
	{
		
	}

    // Maps
    BEGIN_MSG_MAP(WzShare)
        MSG_WM_INITDIALOG(OnInitDialog)
		COMMAND_ID_HANDLER(IDC_WIZARD_SHARE_ADD, OnAdd)
		COMMAND_ID_HANDLER(IDC_WIZARD_SHARE_REMOVE, OnRemove)
		COMMAND_ID_HANDLER(IDC_WIZARD_SHARE_EDIT, OnEdit)
		COMMAND_ID_HANDLER(IDC_WIZARD_SHARE_RENAME, OnRename)
        CHAIN_MSG_MAP(CPropertyPageImpl<WzShare>)
    END_MSG_MAP()

    // Message handlers
    BOOL OnInitDialog ( HWND hwndFocus, LPARAM lParam )
	{
		SetDlgItemText(IDC_WIZARD_SHARE_STATIC, CTSTRING(WIZARD_SHARE_STATIC));
		SetDlgItemText(IDC_WIZARD_SHARE_ADD, CTSTRING(ADD2));
		SetDlgItemText(IDC_WIZARD_SHARE_REMOVE, CTSTRING(REMOVE2));
		SetDlgItemText(IDC_WIZARD_SHARE_EDIT, CTSTRING(WIZARD_SHARE_EDIT));
		SetDlgItemText(IDC_WIZARD_SHARE_RENAME, CTSTRING(RENAME));

		ExListViewCtrl ctrlDirectories;
		ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
		ctrlDirectories.SetExtendedListViewStyle(LVS_EX_LABELTIP | LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER );

		// Prepare shared dir list
		// <Directory Virtual="Windows 7 Service Pack 1">\\FILESERVER\Volume_1\Distr\MS\Win7SP1\</Directory>
		CRect rc;
		ctrlDirectories.GetClientRect(rc);
		ctrlDirectories.InsertColumn(0, CTSTRING(NAME), LVCFMT_LEFT, rc.Width() / 4, 0);
		ctrlDirectories.InsertColumn(1, CTSTRING(DIRECTORY), LVCFMT_LEFT, rc.Width() * 3 / 4, 1);

		StringPairList directories =  ShareManager::getInstance()->getDirectories();

		for (StringPairIter j = directories.begin(); j != directories.end(); ++j)
		{
			int i = ctrlDirectories.insert(ctrlDirectories.GetItemCount(), Text::toT(j->first));
			ctrlDirectories.SetItemText(i, 1, Text::toT(j->second).c_str());
			// ctrlDirectories.SetItemText(i, 2, Text::toT(j->second).c_str());
		}
		ctrlDirectories.Detach();
		return TRUE;
	}

	LRESULT OnAdd(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		tstring target;
		if (WinUtil::browseDirectory(target, m_hWnd))
		{
			// Check If folder already in
			bool bFindF = false;			
			ExListViewCtrl ctrlDirectories;
			ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
			for (int i = 0; i<ctrlDirectories.GetItemCount(); i++)
			{
				LocalArray<TCHAR, FULL_MAX_PATH> path;
				if ( ctrlDirectories.GetItemText(i, 1, path, FULL_MAX_PATH-1) )
				{
					if (target.compare(path) == 0)
					{
						bFindF = true;
						break;
					}
				}
			}

			if (bFindF)
			{
				ctrlDirectories.Detach();
				MessageBox(CTSTRING(WIZARD_SHARE_ALREADYIN), CTSTRING(WIZARD_TITLE), MB_OK | MB_ICONERROR);
				return 0;
			}
			// Search for lastName;
			tstring lastName = 	GetLastNameFormPath(target, ctrlDirectories);

			if (lastName.empty())
			{
				ctrlDirectories.Detach();
				MessageBox(CTSTRING(WIZARD_SHARE_ALREADYINDESC), CTSTRING(WIZARD_TITLE), MB_OK | MB_ICONERROR);
				return 0;
			}
			// Get last folder name		
			int i = ctrlDirectories.insert(ctrlDirectories.GetItemCount(), lastName);
			ctrlDirectories.SetItemText(i, 1, target.c_str());
			ctrlDirectories.Detach();

		}		

		return 0;
	}

	tstring GetLastNameFormPath(tstring target, const ExListViewCtrl& ctrlDirectories)
	{
			tstring lastName = 	Text::toT( Util::getLastDir(Text::fromT(target)));
			tstring lastNameSample = lastName; 
			bool bFindD;
			int iCount = 0;
			do
			{
				bFindD = false;			
				for (int i = 0; i<ctrlDirectories.GetItemCount(); i++)
				{
					LocalArray<TCHAR, FULL_MAX_PATH> path;
					if ( ctrlDirectories.GetItemText(i, 0, path, FULL_MAX_PATH-1) )
					{
						if (lastName.compare(path) == 0)
						{
							bFindD = true;
							break;
						}
					}				
				}
				if (bFindD)
				{
					lastName = lastNameSample;
					lastName += L"_";
					lastName += Text::toT( Util::toString( ++iCount ));
				}
			}while (bFindD);

			return lastName;
	}

	LRESULT OnRemove(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		ExListViewCtrl ctrlDirectories;
		ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
		int iSelected = ctrlDirectories.GetSelectedIndex();
		if (iSelected > -1 && iSelected < ctrlDirectories.GetItemCount())
		{
			LocalArray<TCHAR, FULL_MAX_PATH> path;
			if ( ctrlDirectories.GetItemText(iSelected, 1, path, FULL_MAX_PATH-1) )
			{
				tstring question = path;
				question += CTSTRING(WIZARD_SHARE_DELETEFOLDERQUESTION);
				if (MessageBox(question.c_str(), CTSTRING(WIZARD_TITLE), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 ) == IDYES )
				{
					ctrlDirectories.DeleteItem(iSelected);
				}
			}
		}
		ctrlDirectories.Detach();
		return 0;
	}

	LRESULT OnEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		ExListViewCtrl ctrlDirectories;
		ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
		int iSelected = ctrlDirectories.GetSelectedIndex();
		if (iSelected > -1 && iSelected < ctrlDirectories.GetItemCount())
		{
			LocalArray<TCHAR, FULL_MAX_PATH> path;
			if ( ctrlDirectories.GetItemText(iSelected, 1, path, FULL_MAX_PATH-1) )
			{
				tstring target = path;
				if (WinUtil::browseDirectory(target, m_hWnd))
				{
					bool bFindF = false;
					for (int i = 0; i<ctrlDirectories.GetItemCount(); i++)
					{
						if ( i != iSelected)
						{
							LocalArray<TCHAR, FULL_MAX_PATH> path;
							if ( ctrlDirectories.GetItemText(i, 1, path, FULL_MAX_PATH-1) )
							{
								if (target.compare(path) == 0)
								{
									bFindF = true;
									break;
								}
							}
						}
					}
					if (bFindF)
					{
						ctrlDirectories.Detach();
						MessageBox(CTSTRING(WIZARD_SHARE_ALREADYIN), CTSTRING(WIZARD_TITLE), MB_OK | MB_ICONERROR);
						return 0;
					}
					ctrlDirectories.SetItemText(iSelected, 1, target.c_str());
				}
			}
		}
		ctrlDirectories.Detach();
		return 0;
	}

	LRESULT OnRename(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		ExListViewCtrl ctrlDirectories;
		ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
		int iSelected = ctrlDirectories.GetSelectedIndex();
		if (iSelected > -1 && iSelected < ctrlDirectories.GetItemCount())
		{
			tstring pathSel = Util::emptyStringT;
			tstring pathName = Util::emptyStringT;
			LocalArray<TCHAR, FULL_MAX_PATH> path;
			if ( ctrlDirectories.GetItemText(iSelected, 0, path, FULL_MAX_PATH-1) )
			{
				pathName = path;
			}
			LineDlg virt;
			virt.title = TSTRING(VIRTUAL_NAME);
			virt.description = TSTRING(VIRTUAL_NAME_LONG);
			virt.line = pathName;
			if (virt.DoModal(m_hWnd) == IDOK)
			{
				bool bFindD = false;
				for (int i = 0; i<ctrlDirectories.GetItemCount(); i++)
				{
					if ( i != iSelected)
					{
						LocalArray<TCHAR, FULL_MAX_PATH> path;
						if ( ctrlDirectories.GetItemText(i, 0, path, FULL_MAX_PATH-1) )
						{
							if (virt.line.compare(path) == 0)
							{
								bFindD = true;
								break;
							}
						}				
					}
				}

				if (bFindD)
				{
					ctrlDirectories.Detach();
					MessageBox(CTSTRING(WIZARD_SHARE_ALREADYINDESC), CTSTRING(WIZARD_TITLE), MB_OK | MB_ICONERROR);
					return 0;
				}

				ctrlDirectories.SetItemText(iSelected, 0, virt.line.c_str());
			}
		}
		ctrlDirectories.Detach();
		return 0;
	}

	int OnSetActive()
	{
		SetWizardButtons ( PSWIZB_BACK | PSWIZB_NEXT );
		return 0;
	}

	int OnWizardNext()//OnKillActive()
	{
		// Save 
		StringPairList directories =  ShareManager::getInstance()->getDirectories();

		StringPairList newList;
		StringPairList renameList;
		StringPairList removeList;

		StringPairList directoriesNew;
		ExListViewCtrl ctrlDirectories;
		ctrlDirectories.Attach(GetDlgItem(IDC_WIZARD_SHARE_LIST));
		for (int i = 0; i<ctrlDirectories.GetItemCount(); i++)
		{
			LocalArray<TCHAR, FULL_MAX_PATH> path;
			tstring desc = Util::emptyStringT;
			tstring target = Util::emptyStringT;
			if ( ctrlDirectories.GetItemText(i, 1, path, FULL_MAX_PATH-1) )
			{
				target = path;
			}
			if ( ctrlDirectories.GetItemText(i, 0, path, FULL_MAX_PATH-1) )
			{
				desc = path;
			}				
			StringPair pair = std::make_pair(Text::fromT(desc), Text::fromT(target).c_str());
			directoriesNew.push_back(pair);
			bool bFound = false;
			for (StringPairIter j = directories.begin(); j != directories.end(); ++j)
			{
				// found
				if (j->second.compare(pair.second) == 0 )
				{
					bFound = true;
					if (j->first.compare(pair.first) != 0)
						renameList.push_back( pair );
					break;
				}
			}
			if (!bFound)
				newList.push_back( pair );
		}

		for (StringPairIter i = directories.begin(); i != directories.end(); ++i)
		{
			bool bFind = false;
			for (StringPairIter j = directoriesNew.begin(); j != directoriesNew.end(); ++j)
			{
				if ( i->second.compare(j->second) == 0){
					bFind = true;
					break;
				}
			}	
			if (!bFind)
			{
				// 1. Remove from shareManager
				// removeList.push_back( std::make_pair(i->first, i->second.c_str()) );
				ShareManager::getInstance()->removeDirectory(i->second);
			}
		}

		//for (StringPairIter i = removeList.begin(); i != removeList.end(); ++i)
		//{
		//	ShareManager::getInstance()->removeDirectory(i->second);
		//}
		// 2. Rename
		for (StringPairIter i = renameList.begin(); i != renameList.end(); ++i)
		{
			ShareManager::getInstance()->renameDirectory(i->second, i->first);
		}
		// 3. Add new
		for (StringPairIter i = newList.begin(); i != newList.end(); ++i)
		{
			ShareManager::getInstance()->addDirectory(i->second, i->first);
		}

		ctrlDirectories.Detach();

		return FALSE;       // allow deactivation
	}
	
	int OnKillActive()
	{
		return FALSE;
	}


};



#endif // _WZ_SHARE_H_